const std = @import("std");
const database = @import("../database/db.zig");
const cate_model = @import("../model/cate.zig");

/// 获取首页分类列表
pub fn getHomeCategories() ![]cate_model.Category {
    var db = try database.OpenDb();
    defer db.deinit();

    const query =
        \\SELECT id, name FROM category
    ;

    var stmt = try db.prepare(query);
    defer stmt.deinit();

    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    const allocator = gpa.allocator();

    const rows = try stmt.all(
        cate_model.Category,
        allocator,
        .{},
        .{},
    );

    return rows;
}

/// 获取分类列表
pub fn getCategories() ![]cate_model.Category {
    var db = try database.OpenDb();
    defer db.deinit();

    const query =
        \\SELECT id, name FROM category
    ;

    var stmt = try db.prepare(query);
    defer stmt.deinit();

    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    const allocator = gpa.allocator();

    const rows = try stmt.all(
        cate_model.Category,
        allocator,
        .{},
        .{},
    );

    return rows;
}

/// 添加分类
pub fn addCategory(cate: cate_model.CategoryDtoForCreate) !bool {
    var db = try database.OpenDb();
    defer db.deinit();

    const query =
        \\INSERT INTO category (name) VALUES ($name)
    ;

    var stmt = try db.prepare(query);
    defer stmt.deinit();

    stmt.exec(.{}, .{ .name = cate.name }) catch {
        return false;
    };

    return true;
}

/// 编辑分类
pub fn editCategory(cate: cate_model.CategoryDtoForEdit) !bool {
    var db = try database.OpenDb();
    defer db.deinit();

    const query =
        \\UPDATE category SET name = $name WHERE id = $id
    ;

    var stmt = try db.prepare(query);
    defer stmt.deinit();

    stmt.exec(.{}, .{ .name = cate.name, .id = cate.id }) catch {
        return false;
    };

    return true;
}

/// 删除分类
pub fn deleteCategoryById(id: u32) !bool {
    var db = try database.OpenDb();
    defer db.deinit();

    const query =
        \\DELETE FROM category WHERE id = $id
    ;

    var stmt = try db.prepare(query);
    defer stmt.deinit();

    stmt.exec(.{}, .{ .id = id }) catch {
        return false;
    };

    return true;
}

/// 批量删除分类
pub fn deleteCategoryBatch(ids: []u32) !bool {
    var db = try database.OpenDb();
    defer db.deinit();

    const query =
        \\DELETE FROM category WHERE id = $id
    ;

    for (ids) |id| {
        var stmt = try db.prepare(query);
        defer stmt.deinit();

        stmt.exec(.{}, .{ .id = id }) catch {
            return false;
        };
    }

    return true;
}
